package com.itphy.security;

import com.itphy.util.JwtHelper;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Component
public class TokenAuthenticationProvider implements AuthenticationProvider {

    // 用户拥有的权限
    private final List<GrantedAuthority> authorities = Arrays.asList(new SimpleGrantedAuthority("vip1"));

    //认证资源验证
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        //登录认证是否已经通过
        if (authentication.isAuthenticated()) {
            return authentication;
        }
        String token =null;
        //获取到前端token
        try {
            token=authentication.getPrincipal().toString();
            Map<String, String> tokenData = JwtHelper.verifyToken(token);
            //校验token
            // ....
        }catch (Exception e){
            token=null;
        }
        //token令牌认证，此处token与
        return new UsernamePasswordAuthenticationToken(token, "",authorities);
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
    }

}
